"use client"
import { createContext, useContext, useState, type ReactNode, useEffect } from "react"
import type { DetectionResult } from "@/lib/image-detection"
import { demoCases } from "@/lib/demo-cases"

interface HistoryContextType {
  history: DetectionResult[]
  addHistory: (item: DetectionResult) => void
  clearHistory: () => void
}

const HistoryContext = createContext<HistoryContextType | undefined>(undefined)

export function useHistory() {
  const ctx = useContext(HistoryContext)
  if (!ctx) throw new Error("useHistory must be used within HistoryProvider")
  return ctx
}

export function HistoryProvider({ children }: { children: ReactNode }) {
  // 使用状态来存储历史记录
  const [history, setHistory] = useState<DetectionResult[]>([])

  // 在组件挂载时从localStorage加载历史记录
  useEffect(() => {
    try {
      const data = localStorage.getItem("photo-detect-history")
      if (data) {
        const parsed = JSON.parse(data)
        if (Array.isArray(parsed) && parsed.length > 0) {
          setHistory(parsed)
        } else {
          // 如果没有历史记录或格式不正确，使用示例数据
          setHistory(demoCases)
          localStorage.setItem("photo-detect-history", JSON.stringify(demoCases))
        }
      } else {
        // 如果localStorage中没有数据，使用示例数据
        setHistory(demoCases)
        localStorage.setItem("photo-detect-history", JSON.stringify(demoCases))
      }
    } catch (error) {
      console.error("Error loading history:", error)
      // 出错时使用示例数据
      setHistory(demoCases)
    }
  }, [])

  // 添加新的历史记录
  const addHistory = (item: DetectionResult) => {
    setHistory((prev) => {
      // 确保不添加重复的记录
      const exists = prev.some((i) => i.id === item.id)
      if (exists) return prev

      const next = [item, ...prev]
      // 保存到localStorage
      try {
        localStorage.setItem("photo-detect-history", JSON.stringify(next))
      } catch (error) {
        console.error("Error saving history:", error)
      }
      return next
    })
  }

  // 清除历史记录
  const clearHistory = () => {
    setHistory([])
    try {
      localStorage.removeItem("photo-detect-history")
    } catch (error) {
      console.error("Error clearing history:", error)
    }
  }

  return <HistoryContext.Provider value={{ history, addHistory, clearHistory }}>{children}</HistoryContext.Provider>
}
